#pragma once
#include <glm/glm.hpp>

namespace sg {
	class points {
	private:
		bool _init;
		glm::vec3 *_vertices; // 顶点数据
		int _count; // 顶点数量
		GLuint _vao, _bo;
		int _singleindex;
		double _lastsec;

	private:
		void 
		destroy() {
			if (_vao != 0)
				glDeleteVertexArrays(1, &_vao);
			if (_bo != 0)
				glDeleteBuffers(1, &_bo);
			if (_vertices != NULL)
				delete[] _vertices;
			_init = false;
		}

	public:
		points() 
			: _init(false), _vertices(NULL)
			, _count(0), _vao(0), _bo(0), _singleindex(-1), _lastsec(0) {
				
		}

		~points() {
			destroy();
		}

		void
		init(const std::vector<glm::vec3> &vertices) {
			destroy();

			_count = vertices.size();
			if (_count == 0)
				return;

			_vertices = new glm::vec3[_count];
			for (int i = 0; i < _count; i++) {
				const glm::vec3 &v = vertices[i];
				_vertices[i] = v;
				// printf("[%d]:<%8.3f, %8.3f, %8.3f>\n", i, v.x, v.y, v.z);
			}


			glGenBuffers(1, &_bo);
			glBindBuffer(GL_ARRAY_BUFFER, _bo);
			glBufferData(GL_ARRAY_BUFFER, _count * sizeof(glm::vec3), _vertices, GL_STATIC_DRAW);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glGenVertexArrays(1, &_vao);
			glBindVertexArray(_vao);
				glBindBuffer(GL_ARRAY_BUFFER, _bo);
				glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
				glEnableVertexAttribArray(0);
			glBindVertexArray(0);

			_singleindex = -1;
			_lastsec = 0;
			_init = true;
		}

		void
		draw() {
			if (!_init)
				return;

			glBindVertexArray(_vao);
				glDrawArrays(GL_POINTS, 0, _count);
			glBindVertexArray(0);
		}

		void
		drawsingle(double current) {
			if (!_init)
				return;

			if (_lastsec == 0 || current >= _lastsec) {
				_singleindex = (_singleindex + 1) % _count;
				_lastsec = current + 0.3;
			}

			glBindVertexArray(_vao);
				glDrawArrays(GL_POINTS, _singleindex, 1);
			glBindVertexArray(0);
		}
	};
}
